package cn.com.infcn.monitor.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class IFCBeanUtils {

	/**
	 * 相同属性方法复制数据
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public static void copyProperties(Object source, Object target) throws Exception {

		Method[] methods = source.getClass().getDeclaredMethods();

		Field[] fields = target.getClass().getDeclaredFields();

		for (Method m : methods) {
			String methodName = m.getName();
			for (Field f : fields) {
				String fieldName = f.getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 将属性的首字母转换为大写
				String getMethodName = "get" + firstLetter + fieldName.substring(1);
				String setMethodName = "set" + firstLetter + fieldName.substring(1);
				if (getMethodName.equals(methodName)) {
					try {
						m.setAccessible(true);
						Object value = m.invoke(source);
						Method setMethod = target.getClass().getMethod(setMethodName, new Class[] { f.getType() });// 注意set方法需要传入参数类型
						setMethod.invoke(target, new Object[] { value });
					} catch (NoSuchMethodException e) {
					} catch (IllegalArgumentException e){
					}
				}
			}
		}
	}
	
	/**
	 * 相同属性方法复制数据
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public static void copyProperties(Object source, Class<?> sourceClazz, Object target) throws Exception {

		Method[] methods = sourceClazz.getDeclaredMethods();

		Field[] fields = target.getClass().getDeclaredFields();

		for (Method m : methods) {
			String methodName = m.getName();
			for (Field f : fields) {
				String fieldName = f.getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 将属性的首字母转换为大写
				String getMethodName = "get" + firstLetter + fieldName.substring(1);
				String setMethodName = "set" + firstLetter + fieldName.substring(1);
				if (getMethodName.equals(methodName)) {
					try {
						m.setAccessible(true);
						Object value = m.invoke(source);

						Method setMethod = target.getClass().getMethod(setMethodName, new Class[] { f.getType() });// 注意set方法需要传入参数类型
						setMethod.invoke(target, new Object[] { value });
					} catch (NoSuchMethodException e) {
					}
				}
			}
		}
	}
	
}
